package com.goldplusgold.tradedelay.app.home.live.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.imageloader.lib.IShow;
import com.goldplusgold.live.LVDataManager;
import com.goldplusgold.live.bean.CIntroBean;
import com.goldplusgold.live.bean.QuestionBean;
import com.goldplusgold.live.bean.VRecordBean;
import com.example.account.manager.AppCacheSharedPreferences;
import com.goldplusgold.support.lib.flow.FlowLayout;
import com.goldplusgold.support.lib.flow.TagAdapter;
import com.goldplusgold.support.lib.flow.TagFlowLayout;
import com.goldplusgold.support.lib.utils.ScreenSizeUtil;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.ErrorCodeConstant;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.tradedelay.app.base.widget.QuitDialog;
import com.goldplusgold.tradedelay.app.home.live.ColumnInfoActivity;
import com.goldplusgold.tradedelay.app.home.live.LiveConstants;
import com.goldplusgold.tradedelay.app.home.live.LiveDetailActivity;
import com.example.account.manager.ParmasKey;
import com.goldplusgold.tradedelay.app.home.live.base.LiveBaseCallBack;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/7/26.
 */

public class ColumnInfoAdapter extends RecyclerView.Adapter {
    public static final int CINTRODEAIL_INFO = 0 ;
    public static final int CINTRODEAIL_HEAD = 1 ;
    public static final int CINTRODEAIL_ITEM = 2 ;

    public static final int RECORDS_HEAD = 3 ;
    public static final int RECORDS_ITEM = 4 ;

    public static final int LIVING_ITEM = 6;

    private Context context ;
    private CIntroBean cIntroBean ;
    private List<VRecordBean> recordLists ;
    private ColumnInfoAdapterListener listener ;
    private String columnID ;
    private int entryType ;

    public void setcIntroBeans(CIntroBean cIntroBean) {
        this.cIntroBean = cIntroBean;
        notifyDataSetChanged();
    }


    public ColumnInfoAdapter(int entryType , Context context , CIntroBean cIntroBean , List<VRecordBean> recordLists ,String columnID, ColumnInfoAdapterListener listener){
        this.entryType = entryType ;
        this.context = context ;
        this.cIntroBean = cIntroBean ;
        this.recordLists = recordLists ;
        this.listener = listener ;
        this.columnID = columnID ;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View ItemView = null ;
        switch (viewType){
            case CINTRODEAIL_INFO :
                ItemView = LayoutInflater.from(context).inflate(R.layout.live_detail_layout_description , parent ,false);
                return new ColumnInfoHolder(ItemView);
            case CINTRODEAIL_HEAD :
                ItemView = LayoutInflater.from(context).inflate(R.layout.live_speaker_header , parent ,false);
                return new SpeakerHeaderHolder(ItemView);
            case CINTRODEAIL_ITEM :
                ItemView = LayoutInflater.from(context).inflate(R.layout.live_column_analysts_item , parent ,false);
                return new SpeakerItemHolder(ItemView) ;
            case RECORDS_HEAD :
                ItemView = LayoutInflater.from(context).inflate(R.layout.live_history_header , parent , false);
                return new HistoryHeaderHolder(ItemView);
            case RECORDS_ITEM :
                ItemView = LayoutInflater.from(context).inflate(R.layout.live_history_item , parent , false);
                return new HistoryItemHolder(ItemView);
            case LIVING_ITEM :
                ItemView = LayoutInflater.from(context).inflate(R.layout.live_living_item , parent , false);
                return new LivingItemHolder(ItemView);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(holder instanceof ColumnInfoHolder){
            ColumnInfoHolder h = (ColumnInfoHolder) holder;
            IShow.getInstance().showCircle(context ,cIntroBean.getColumnIcon(),h.description_icon_img);
            h.description_title_txt.setText(cIntroBean.getColumnName());
            h.description_intro_txt.setText(cIntroBean.getColumnIntro());
            refreshFollowView(cIntroBean.isLikeFlag() , h);
        }

        if(holder instanceof SpeakerItemHolder){
            SpeakerItemHolder h = (SpeakerItemHolder) holder;
            IShow.getInstance().showCircle(context,cIntroBean.getAnalysts().get(position - 2).getAnalystIcon(),h.mSpeakerIconIv);
            h.mSpeakerNameTv.setText(cIntroBean.getAnalysts().get(position - 2).getAnalystName());
            h.mSpeakerMessageTv.setText(cIntroBean.getAnalysts().get(position - 2).getAnalystIntro());
            String TagStrs = cIntroBean.getAnalysts().get(position - 2).getAnalystTags();
            setTags(TagStrs , h.mTagsFlowLayout);
        }

        if(holder instanceof LivingItemHolder){
            LivingItemHolder h = (LivingItemHolder) holder;
            IShow.getInstance().showRound(context , cIntroBean.getLiveIcon() , h.live_icon_iv ,
                    ScreenSizeUtil.dip2px(context , 132) , ScreenSizeUtil.dip2px(context ,75));
            h.living_name_tv.setText(cIntroBean.getLiveName());
            LivingState(h , cIntroBean);
            if(cIntroBean.isPrevueFlag()) {
                h.living_herald_tv.setText("节目预告:  " + cIntroBean.getLivePrevue() + " " + cIntroBean.getLivePrevueTime());
            }else{
                h.living_herald_tv.setText("节目预告:  暂无");
            }
        }

        if(holder instanceof HistoryItemHolder){
            int analyNum = 0 ;
            if(cIntroBean.getAnalysts() != null && cIntroBean.getAnalysts().size() !=0){
                analyNum = cIntroBean.getAnalysts().size();
            }

            int realpostion = position - 4 - analyNum;

            HistoryItemHolder h = (HistoryItemHolder) holder;

            h.itemView.setTag(realpostion);

            h.time.setText(recordLists.get(realpostion).getLiveTime());
            IShow.getInstance().showRound(context,recordLists.get(realpostion).getLiveIcon(),h.back,
                    ScreenSizeUtil.dip2px(context ,130 ) , ScreenSizeUtil.dip2px(context ,80 ));
            h.title.setText(recordLists.get(realpostion).getLiveName());
            if(recordLists.get(realpostion).getLiveType() == LiveConstants.LiveType.WORD_LIVE){
                h.category.setText("文字直播");
            } else{
                h.category.setText("视频直播");
            }
        }
    }




    @Override
    public int getItemCount() {
        if(cIntroBean == null || cIntroBean.getAnalysts() == null || recordLists == null){
            return 0 ;
        }

        int analyNum = 0 ;
        if(cIntroBean.getAnalysts() != null && cIntroBean.getAnalysts().size() !=0){
            analyNum = cIntroBean.getAnalysts().size();
        }

        int recordNum = 0 ;
        if(recordLists != null && recordLists.size() != 0 ){
            recordNum = recordLists.size() ;
        }
        //栏目详情 + 主讲人 header + 主讲人 Lists + 当前直播 + 历史直播 header + 历史直播 lists
        return 1 + 1 + analyNum + 1 + 1 + recordNum ;
    }


    @Override
    public int getItemViewType(int position) {
        int analyNum = 0 ;
        if(cIntroBean.getAnalysts() != null && cIntroBean.getAnalysts().size() !=0){
            analyNum = cIntroBean.getAnalysts().size();
        }

        if(position == 0 ){
            return CINTRODEAIL_INFO ;
        }else if(position == 1){
            return CINTRODEAIL_HEAD ;
        }else if(position < analyNum + 2 ){
            return CINTRODEAIL_ITEM ;
        }else if(position == analyNum + 2){
            return LIVING_ITEM ;
        }else if(position == analyNum + 3){
            return RECORDS_HEAD ;
        }else{
            return RECORDS_ITEM;
        }
    }

    public class ColumnInfoHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.description_icon_img)
        ImageView description_icon_img;
        @BindView(R.id.description_title_txt)
        TextView description_title_txt;
        @BindView(R.id.description_intro_txt)
        TextView description_intro_txt;
        @BindView(R.id.live_item_layout_detail_follow)
        LinearLayout live_item_layout_detail_follow ;
        @BindView(R.id.live_item_layout_detail_follow_img)
        ImageView live_item_layout_detail_follow_img ;
        @BindView(R.id.live_item_layout_detail_follow_txt)
        TextView live_item_layout_detail_follow_txt ;

        @OnClick(R.id.live_item_layout_detail_follow)
        void onClick(View view){
            changeFollow(cIntroBean.isLikeFlag() , ColumnInfoHolder.this);
        }

        public ColumnInfoHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this , itemView);
        }
    }

    public class SpeakerHeaderHolder extends RecyclerView.ViewHolder{

        public SpeakerHeaderHolder(View itemView) {
            super(itemView);
        }
    }

    public class SpeakerItemHolder extends RecyclerView.ViewHolder{

        @BindView(R.id.live_column_layout_icon)
        ImageView mSpeakerIconIv ;
        @BindView(R.id.live_column_layout_name)
        TextView mSpeakerNameTv ;
        @BindView(R.id.live_column_layout_intro)
        TextView mSpeakerMessageTv ;
       // @BindView(R.id.live_column_layout_tags)
       // LinearLayout mSpeakerTagsLayout ;
        @BindView(R.id.live_flow_tags)
        TagFlowLayout mTagsFlowLayout ;

        public SpeakerItemHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this , itemView);
        }
    }

    public class HistoryHeaderHolder extends RecyclerView.ViewHolder{

        public HistoryHeaderHolder(View itemView) {
            super(itemView);
        }
    }

    public class HistoryItemHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.video_item_layout_txt_title)
        TextView title;
        @BindView(R.id.video_item_layout_img_back)
        public ImageView back;
        @BindView(R.id.video_item_layout_txt_time)
        public TextView time;
        @BindView(R.id.video_item_layout_img_control)
        public ImageView control;
        @BindView(R.id.video_item_layout_txt_category)
        public TextView category;

        public HistoryItemHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this , itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = (int) v.getTag();
                    listener.HistoryItemClick(pos);
                }
            });
        }
    }

   /* public class LivingHeaderHolder extends RecyclerView.ViewHolder{

        public LivingHeaderHolder(View itemView) {
            super(itemView);
        }
    }*/

    public class LivingItemHolder extends RecyclerView.ViewHolder{

        @BindView(R.id.live_icon_iv)
        ImageView live_icon_iv ;
        @BindView(R.id.living_name_tv)
        TextView living_name_tv ;
        @BindView(R.id.living_state_tv)
        TextView living_state_tv ;
        @OnClick(R.id.living_rl)
        void gotoLiveDetail(View view){
            Intent intent = new Intent(context, LiveDetailActivity.class);
            intent.putExtra("liveID",cIntroBean.getLiveID());
            intent.putExtra("roomID",cIntroBean.getRoomID());
            if(cIntroBean.getLiveType()== 0){
                intent.putExtra("type", LiveDetailActivity.LiveDetailType.TEXT_LIVE);
            }else{
                intent.putExtra("type", LiveDetailActivity.LiveDetailType.LIVE);
            }
            context.startActivity(intent);
           /* if(entryType == ColumnInfoActivity.TYPE_FROM_MIDDLE){
                ((Activity)context).finish();
            }*/
        }
        @BindView(R.id.living_herald_tv)
        TextView living_herald_tv ;

        public LivingItemHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this , itemView);
        }
    }

    public void setTags(String tags , final TagFlowLayout tagFlowLayout){
        if(tags == null || "".equals(tags)){
            return;
        }
        String [] tgs = tags.split(",");
        tagFlowLayout.setAdapter(new TagAdapter<String>(tgs){

            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(context).inflate(R.layout.item_live_text,
                        tagFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        });
    }

    private void LivingState(LivingItemHolder h , CIntroBean bean) {
        Drawable leftDrawable = context.getResources().getDrawable(R.drawable.live_icon_small_end);
        leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());

        Drawable leftDrawable1 = context.getResources().getDrawable(R.drawable.live_icon_middle);
        leftDrawable1.setBounds(0, 0, leftDrawable1.getMinimumWidth(), leftDrawable1.getMinimumHeight());
        //0 , 15点击进去没有URL,要做判断处理,10点击进去 有URL ,
        switch (bean.getLiveStatus()){
            case  0  :
            case  20 :
                h.living_state_tv.setText(bean.getLiveTime() + " 即将开播");
                h.living_state_tv.setBackground(context.getResources().getDrawable(R.drawable.shape_follow_select));
                h.living_state_tv.setTextColor(context.getResources().getColor(R.color.color_gold) );
                break;
            case 10:
            case 15:
                h.living_state_tv.setCompoundDrawables(leftDrawable , null , null , null);
                h.living_state_tv.setBackground(context.getResources().getDrawable(R.drawable.shape_follow_normal));
                h.living_state_tv.setTextColor(context.getResources().getColor(R.color.follower_text) );
                h.living_state_tv.setText("直播结束");
                break;
            case 30:
                h.living_state_tv.setTextColor(context.getResources().getColor(R.color.color_gold) );
                h.living_state_tv.setBackground(context.getResources().getDrawable(R.drawable.shape_follow_select));
                h.living_state_tv.setCompoundDrawables(leftDrawable1 , null , null , null);
                if(bean.getLiveType() == 0){
                    h.living_state_tv.setText("文字直播中");
                }else{
                    h.living_state_tv.setText("视频直播中");
                }
                break;
            default:
                h.living_state_tv.setTextColor(context.getResources().getColor(R.color.follower_text) );
                h.living_state_tv.setBackground(context.getResources().getDrawable(R.drawable.shape_follow_normal));
                h.living_state_tv.setCompoundDrawables(leftDrawable , null , null , null);
                h.living_state_tv.setText("未知状态");
                break;
        }
    }

    private void changeFollow(final boolean likeFlag , final ColumnInfoHolder holder){
        if(!AppCacheSharedPreferences.getCacheBoolean(ParmasKey.login_state , false)){
            QuitDialog quitDialog = new QuitDialog(context);

            quitDialog.setMessage("请先登录后关注");
            quitDialog.show();
            return;
        }
        if(likeFlag){
            LVDataManager.getInstance().follow(columnID, new LiveBaseCallBack<QuestionBean>(context) {
                @Override
                public void onResponse(Call<QuestionBean> call, Response<QuestionBean> response) {

                    super.onResponse(call , response);
                    if(response.body().getStatus()){
                        cIntroBean.setLikeFlag(false);
                        refreshFollowView(cIntroBean.isLikeFlag() , holder);
                    }else{
                        Toast.makeText(context, "取消关注失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<QuestionBean> call, Throwable t) {
                    Toast.makeText(context , "网络断片~~" , Toast.LENGTH_SHORT);
                }
            });
        } else{
            LVDataManager.getInstance().unFollow( columnID, new LiveBaseCallBack<QuestionBean>(context) {
                @Override
                public void onResponse(Call<QuestionBean> call, Response<QuestionBean> response) {
                    super.onResponse(call , response);
                    if(response.body().getStatus()){
                        cIntroBean.setLikeFlag(true);
                        refreshFollowView(cIntroBean.isLikeFlag() , holder);
                    }else{
                        Toast.makeText(context, "关注失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<QuestionBean> call, Throwable t) {
                    Toast.makeText(context , "网络断片~~" , Toast.LENGTH_SHORT);
                }
            });
        }
    }

    private void refreshFollowView(boolean likeFlag, ColumnInfoHolder holder) {
        if(likeFlag){
            holder.live_item_layout_detail_follow.setBackgroundResource(R.drawable.shape_follow_normal);
            holder.live_item_layout_detail_follow_img.setBackgroundResource(R.drawable.live_icon_follower);
            holder.live_item_layout_detail_follow_txt.setTextColor(context.getResources().getColor(R.color.follower_text));
            holder.live_item_layout_detail_follow_txt.setText(context.getString(R.string.live_ready_follow));
        } else{
            holder.live_item_layout_detail_follow.setBackgroundResource(R.drawable.shape_follow_select);
            holder.live_item_layout_detail_follow_img.setBackgroundResource(R.drawable.live_icon_follow);
            holder.live_item_layout_detail_follow_txt.setTextColor(context.getResources().getColor(R.color.color_gold));
            holder.live_item_layout_detail_follow_txt.setText(context.getString(R.string.live_follow));
        }
    }

    public interface ColumnInfoAdapterListener{
        public void HistoryItemClick(int realpostion);
    }




}
